import java.io.*;
import java.net.*;
import java.util.*;

public class TCP2Qdemo2 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9002);
        System.out.println("服务器在9002端口监听，等待连接...");
        Socket socket = serverSocket.accept();
        // 用于接收客户端请求的线程
        new Thread(new GetClientSend(socket)).start();

        // 用于发送响应给客户端的线程
        new Thread(new ToClientCode(socket)).start();
    }
}

class GetClientSend implements Runnable {
    private Socket serverSocket;

    public GetClientSend(Socket serverSocket) {
        this.serverSocket = serverSocket;
    }

    @Override
    public void run() {
        try {
            while (true) {
                InputStream inputStream = serverSocket.getInputStream();
                byte[] buffer = new byte[1024];
                int bytesRead = inputStream.read(buffer);
                String requestData = new String(buffer, 0, bytesRead);
                System.out.println("\n收到客户端请求：" + requestData);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ToClientCode implements Runnable {
    private Socket serverSocket;

    public ToClientCode(Socket serverSocket) {
        this.serverSocket = serverSocket;
    }

    @Override
    public void run() {
        try {
            while (true) {
                System.out.println("1");
                Scanner scanner = new Scanner(System.in);
                System.out.print("请输入要发送给客户端的响应：");
                String responseData = scanner.nextLine();
                System.out.println("向客户端发送响应数据：" + responseData);


                OutputStream outputStream = serverSocket.getOutputStream();
                outputStream.write(responseData.getBytes());
                outputStream.flush(); // 刷新输出流，确保数据被发送出去。
                Thread.sleep(500); // 网络没那么快，等待一下。
                System.out.println("2");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}